package com.foreknow.elm.service.impl;

import com.foreknow.elm.dao.CartDao;
import com.foreknow.elm.dao.impl.CartDaoImpl;
import com.foreknow.elm.po.Cart;
import com.foreknow.elm.service.CartService;
import com.foreknow.elm.util.DBUtil;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class CartServiceImpl implements CartService {
    @Override
    public List<Cart> listCart(Cart cart) {
        List<Cart> list = new ArrayList<>();
        CartDao cartDao = new CartDaoImpl();
        try {
            list = cartDao.listCart(cart);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close();
        }
        return list;
    }

    @Override
    public int saveCart(String userId, Integer businessId, Integer foodId) {
        int result = 0;
        try {
            DBUtil.beginTransaction();//开启事务
            CartDaoImpl cartDao = new CartDaoImpl();
            result = cartDao.saveCart(userId, businessId, foodId);
            DBUtil.commitTransaction();//提交事务
        } catch (Exception e) {
            try {
                DBUtil.rollbackTransaction();//回滚事务
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
            }
            finally {
               DBUtil.close();
            }
        return result;
    }

        @Override
        public int updateCart(String userId, Integer businessId, Integer foodId, Integer quantity) {
            int result = 0;
            try {
                DBUtil.beginTransaction();
                CartDaoImpl cartDao = new CartDaoImpl();
                result = cartDao.updateCart(userId, businessId, foodId, quantity);
                DBUtil.commitTransaction();
            } catch (Exception e) {
                try {
                    DBUtil.rollbackTransaction();
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
                e.printStackTrace();
            } finally {
                DBUtil.close();
            }
            return result;
        }

        @Override
        public int removeCart (Cart cart){
            int result = 0;
            try {
                DBUtil.beginTransaction();
                CartDaoImpl cartDao = new CartDaoImpl();
                result = cartDao.removeCart(cart);
                DBUtil.commitTransaction();

            } catch (Exception e) {
                try {
                    DBUtil.rollbackTransaction();
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
                e.printStackTrace();
            } finally {
                DBUtil.close();
            }
            return result;
        }


    }


